package com.wen.top.Utils;

import lombok.extern.slf4j.Slf4j;

import javax.servlet.http.HttpServletRequest;
import java.net.Inet4Address;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.util.Enumeration;

/**
 * @ClassName: IpUtil
 * @Description: IP工具类
 * @Author: 王懿恺
 * @Date: 2019/2/18 19:30
 * @Version: 1.0
 **/
@Slf4j
public class IpUtil {
	/**
	 * 获取本机ip
	 * @return
	 */
	public static String getSerIp(){
		String clientIp ="";
		// 根据网卡取本机配置的IP,定义网络接口枚举类
		Enumeration<NetworkInterface> allNetInterfaces;
		try {
			//获得网络接口
			allNetInterfaces = NetworkInterface.getNetworkInterfaces();
			//声明一个InetAddress类型ip地址
			InetAddress ip = null;
			//遍历所有的网络接口
			while (allNetInterfaces.hasMoreElements())
			{
				NetworkInterface netInterface = allNetInterfaces.nextElement();
				//同样再定义网络地址枚举类
				Enumeration<InetAddress> addresses = netInterface.getInetAddresses();
				while (addresses.hasMoreElements())
				{
					ip = addresses.nextElement();
					//InetAddress类包括Inet4Address和Inet6Address
					if (ip != null && (ip instanceof Inet4Address))
					{
						if(!ip.getHostAddress().equals("127.0.0.1")){
							clientIp= ip.getHostAddress();
						}
					}
				}
			}
		} catch (SocketException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return clientIp;
	}

	/**
	 * 获取客户端真实ip
	 * @param request
	 * @return
	 */
	public static String getIpAddr(HttpServletRequest request) {
		String ip = request.getHeader("x-forwarded-for");
		log.info("x-forwarded-for ip: " + ip);
		if (ip != null && ip.length() != 0 && !"unknown".equalsIgnoreCase(ip)) {
			// 多次反向代理后会有多个ip值，第一个ip才是真实ip
			if( ip.indexOf(",")!=-1 ){
				ip = ip.split(",")[0];
			}
		}
		if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
			ip = request.getHeader("Proxy-Client-IP");
			log.info("Proxy-Client-IP ip: " + ip);
		}
		if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
			ip = request.getHeader("WL-Proxy-Client-IP");
			log.info("WL-Proxy-Client-IP ip: " + ip);
		}
		if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
			ip = request.getHeader("HTTP_CLIENT_IP");
			log.info("HTTP_CLIENT_IP ip: " + ip);
		}
		if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
			ip = request.getHeader("HTTP_X_FORWARDED_FOR");
			log.info("HTTP_X_FORWARDED_FOR ip: " + ip);
		}
		if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
			ip = request.getHeader("X-Real-IP");
			log.info("X-Real-IP ip: " + ip);
		}
		if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
			ip = request.getRemoteAddr();
			log.info("getRemoteAddr ip: " + ip);
		}
		log.info("获取客户端ip: " + ip);
		return ip;
	}

	public static void main(String[] args) {
		System.out.println(getSerIp());
	}
}
